package com.fastjars.business.spring.resolver.param;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor;

import javax.servlet.ServletRequest;

/**
 * EmptyArgumentHandlerModelAttributeMethodProcessor
 * <p>使用说明：</p>
 * <pre>
 * &lt;mvc:annotation-driven&gt;
 *     &lt;mvc:argument-resolvers&gt;
 *         &lt;bean class="com.fastjars.core.spring.resolver.param.EmptyArgumentHandlerModelAttributeMethodProcessor"&gt;
 *             &lt;constructor-arg name="annotationNotRequired" value="true"/&gt;
 *         &lt;/bean&gt;
 *     &lt;/mvc:argument-resolvers&gt;
 * &lt;/mvc:annotation-driven&gt;
 * </pre>
 * @author Brant Liu <br> 邮箱：<br>lbf1988@qq.com <br>日期：<br>2018/03/21
 * @version 1.0.0
 */
public class EmptyArgumentHandlerModelAttributeMethodProcessor extends ServletModelAttributeMethodProcessor implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    public EmptyArgumentHandlerModelAttributeMethodProcessor(boolean annotationNotRequired) {
        super(annotationNotRequired);
    }

    @Override
    protected void bindRequestParameters(WebDataBinder binder, NativeWebRequest request) {
        EmptyArgumentHandlerRequestDataBinder toNullRequestDataBinderBinder = new EmptyArgumentHandlerRequestDataBinder(binder.getTarget(), binder.getObjectName());
        RequestMappingHandlerAdapter requestMappingHandlerAdapter = applicationContext.getBean(RequestMappingHandlerAdapter.class);
        requestMappingHandlerAdapter.getWebBindingInitializer().initBinder(toNullRequestDataBinderBinder);
        toNullRequestDataBinderBinder.bind(request.getNativeRequest(ServletRequest.class));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
